{extend name="../../base/view/common/base" /}
<!-- 主体 -->
{block name="body"}

<div class="layui-col-lg12 layui-col-md12 layui-col-sm12">

    <div class="">
        <form class="layui-form gg-form-bar border-t border-x">
            <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="oderNum" placeholder="单据编号" class="layui-input" autocomplete="off" />
            </div>
         
             <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="p_name" placeholder="供应商名称" class="layui-input" autocomplete="off" />
            </div>
             <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="md_name" placeholder="产品名称" class="layui-input" autocomplete="off" />
            </div>
             <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="md_bar_code" placeholder="产品编码" class="layui-input" autocomplete="off" />
            </div>
             <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="ywlx" placeholder="业务类型" class="layui-input" autocomplete="off" />
            </div>
             <div class="layui-input-inline" style="width:300px;">
                <input type="text" name="ydBm" placeholder="源单编码" class="layui-input" autocomplete="off" />
            </div>
            <div class="layui-input-inline" style="width:300px;">
                <input type="text" id="reconcileDate" readonly name="reconcileDate" placeholder="对账日期" class="layui-input" autocomplete="off" />
            </div>
            <div class="layui-input-inline" style="width:300px;">
                <select name="i_status" >
                    <option value="">所有状态</option>
                    {foreach ['','草稿','已确认']  as $key=>  $v}
                    <option value="{$key}">{$v}</option>
                    {/foreach}
                </select>
            </div>

            <div class="layui-input-inline" style="width:150px;">
                <button class="layui-btn layui-btn-normal" lay-submit="" lay-filter="webformIndex"><i class="layui-icon layui-icon-search mr-1"></i>搜索</button>
                <button type="reset" class="layui-btn layui-btn-reset" lay-filter="reset">清空</button>
            </div>
        </form>
        <div class="p-3">
            <div>
                <table class="layui-hide" id="treeTable" lay-filter="treeTable"></table>
            </div>
        </div>
    </div>
</div>
<div id="tip_modal" style="display: none">
    <a class="layui-btn layui-btn-sm " id="addB" href="javascript:" data-modal="{:url('addMx')}">产品对账</a>
    <a class="layui-btn layui-btn-sm " id="addJ" href="javascript:" data-modal="{:url('addPrice')}">金额对账</a>
</div>
<script type="text/html" id="toolbarDemo">
    <a class="layui-btn layui-btn-sm add-menu" lay-event="add" href="javascript:" >产品对账</a>
    <a class="layui-btn layui-btn-sm layui-btn-danger" lay-event="jeDz"  href="javascript:" >金额对账</a>
<!--    <a class="layui-btn layui-btn-sm layui-btn-primary" id="import"  lay-event="import">导入</a>-->
<!--    <a href="{__EXPORTMODE__}/对账导入模板.xlsx" download="" class="layui-btn layui-btn-sm layui-btn-primary">导入模板</a>-->
    <a class="layui-btn layui-btn-sm layui-btn-danger " lay-event="dels" >删除</a>
    <a class="layui-btn layui-btn-sm layui-btn-primary " lay-event="onSure" >批量确认</a>
    <a class="layui-btn layui-btn-sm layui-btn-primary " lay-event="onCancel" >批量撤销</a>
    <a class="layui-btn layui-btn-sm layui-btn-normal " target="_blank" href="{:url('exportData')}">导出</a>

</script>
<script type="text/html" id="actionBar">
<!--    <a target="_blank" href="{:url('printPage')}?id={{d.id}}" class="layui-btn layui-btn-primary  layui-btn-xs">打印对账</a>-->
    <button class="layui-btn layui-btn-normal  layui-btn-xs"  lay-event="edit">编辑</button>
    <!--    <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</button>-->
</script>
{/block}
<!-- /主体 -->

<!-- 脚本 -->
{block name="script"}
<script>
    const moduleInit = ['tool'];
    var mStatus=['','草稿','已确认'];
    var indexTable='';
    function gouguInit() {
        var treeTable = layui.treeTable, tool = layui.tool,form = layui.form,laydate=layui.laydate;
        var mxTb = layui.table
        var priceTb = layui.table
        var upload=layui.upload;
        var tableIns = treeTable.render({
            elem: '#treeTable'
            , url: "{:url('index')}"
            ,toolbar: '#toolbarDemo',
            defaultToolbar:  ['filter',  'exports']
            , tree: { // treeTable 特定属性集
                customName: {name: 'name'},
                data: {},
                view: {showIcon: false},
                async: {},
                callback: {}
            }
            , cellMinWidth: 80
            , cols: [[
                {type: 'checkbox', fixed: 'left' },
                {fixed: 'left',field: 'id',title: 'ID' ,unresize: true,hide:true},
                // {field: 'id', width: 80, title: 'ID号', align: 'center'},
                 {field: 'orderNum',  title: '单据编号'}
                , {field: 'pName',  title: '供应商名称'}
                , {field: 'bar_code',  title: '产品编码'}
                , {field: 'mdName',  title: '产品名称'}
                , {field: 'specs',  title: '规格型号'}
                , {field: 'ywlx',  title: '业务类型'}
                , {field: 'fromOrderNum',  title: '源单编码'}
                , {field: 'reconcileNum',  title: '对账数量'}
                , {field: 'reconcilePrice',  title: '对账金额'}
                , {field: 'skMoney',  title: '付款金额'}
                , {field: 'reconcileDate',  title: '对账日期'}
                 , {field: 'status', title: '状态',  align: 'center',templet:function (d) {
                        return mStatus[d.status];
                    }}
                , {title: '操作',fixed: 'right',width: 200,  align: 'center'
                    , toolbar: '#actionBar'
                }
            ]]
            , page: true
        });
        indexTable=tableIns;
        //监听搜索提交
        form.on('submit(webformIndex)', function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        //表头工具栏事件
        // $('.add-menu').on('click', function () {
        //     $("#addB").click()
        //     return;
        // });

        //操作按钮
        treeTable.on('tool(treeTable)', function (obj) {
            console.log(obj);
            if (obj.event === 'add') {
                tool.side("{:url('add')}?pid=" + obj.data.id);
                return;
            }
            if (obj.event === 'edit') {
                tool.side("{:url('add')}?id=" + obj.data.id);
                return;
            }
            if (obj.event === 'del') {
                layer.confirm('确定要删除吗?', {icon: 3, title: '提示'}, function (index) {
                    let callback = function (e) {
                        layer.msg(e.msg);
                        if (e.code == 0) {
                            obj.del();
                        }
                    }
                    tool.delete("{:url('delete')}", {id: obj.data.id}, callback);
                    layer.close(index);
                });
            }
        });
        treeTable.on('toolbar(treeTable)', function(obj){
            var checkStatus = treeTable.checkStatus(obj.config.id);
            console.log(checkStatus)
            switch(obj.event){
                case 'add':
                    $("#addB").click()
                    break;
                case 'dels':
                    var data = checkStatus.data;
                    var ids=[]
                    if (data.length){
                        data.forEach(function (value,index) {
                            console.log('value',value)
                            ids.push(value.id)
                        })
                        layer.confirm('确定要删除吗?', {icon: 3, title: '提示'}, function (index) {
                            let callback = function (e) {
                                layer.msg(e.msg);
                                if (e.code == 0) {
                                    tableIns.reload();
                                }
                            }
                            tool.delete("{:url('delete')}", {id: ids.join(',')}, callback);
                            layer.close(index);
                        });

                    }else {
                        layer.msg('请选择数据');
                    }

                    break;
                case 'import':
                    var loadingIndex='';
                    upload.render({
                        elem: '#import'
                        ,url: "{:url('importData')}"
                        ,accept: 'file'
                        ,exts: 'xlsx',
                        before:function (res) {
                            loadingIndex=layer.load(1,{
                                shade: [0.5,'#a09b9b']
                            });
                        }
                        ,done: function(res){
                            layer.msg(res.msg)
                            layer.close(loadingIndex)
                            setTimeout(function () {
                                location.reload()
                            },2000)
                        },
                        error(e){
                            layer.msg('网络异常请稍后再试')
                            layer.close(loadingIndex)
                        }
                    });
                    break;
                    case 'jeDz':
                        $("#addJ").click()
                    break;

                case 'onSure':
                    var data = checkStatus.data;
                    var ids=[]
                    if (data.length){
                        data.forEach(function (value,index) {
                            console.log('value',value)
                            ids.push(value.id)
                        })
                        onSure(ids)
                    }else {
                        layer.msg('请选择数据');
                    }
                    break;
                    case 'onCancel':
                    var data = checkStatus.data;
                    var ids=[]
                    if (data.length){
                        data.forEach(function (value,index) {
                            console.log('value',value)
                            ids.push(value.id)
                        })
                        onCancel(ids)
                    }else {
                        layer.msg('请选择数据');
                    }
                    break;
            };
        })

        var mxTableIns = mxTb.render({
            elem: '#mxTable'
            , url: "{:url('addMx')}"
            , method: 'post'
            , toolbar: '#mxToolbarDemo',
            defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {type: 'checkbox', fixed: 'left'},
                {fixed: 'left', field: 'id', title: 'ID', unresize: true, hide: true}
                // ,{field: 'id', width: 80, title: 'ID号', align: 'center'}
                , {field: 'pName', title: '供应商'}
                , {field: 'mdName', title: '产品名称'}
                , {field: 'bar_code', title: '产品编码'}
                , {field: 'specs', title: '规格型号'}
                , {field: 'type', title: '业务类型'}
                , {field: 'g_orderNum', title: '关联单据编号'}
                , {field: 'unReconcile', title: '未对账数量'}
                , {field: 'reconcileNum', width:100, title: '对账数量',edit:"text"}
                , {field: 'reconcilePrice', width:100, title: '对账金额'}
            ]]
            , page: true
        });
        //监听搜索提交
        form.on('submit(webform)', function (data) {
            mxTableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        //表头工具栏事件
        mxTb.on('toolbar(mxTable)', function (obj) {
            var checkStatus = mxTb.checkStatus(obj.config.id);
            console.log(checkStatus)
            switch (obj.event) {
                case 'add':
                    break;
                case 'subt':
                    var data = checkStatus.data;
                    var ids = []
                    if (data.length) {
                        data.forEach(function (value, index) {
                            ids.push(value)
                        })

                        saveAddMx(ids)
                        layer.close(layTip)

                    } else {
                        layer.msg('请选择数据');
                    }

                    break;
                case 'import':

                    break;

            }
            ;
        })
        mxTb.on('edit(mxTable)', function(obj){
            var value = obj.value // 得到修改后的值
            var price=0;
            var data = obj.data
            if(! /^-?\d+$/.test(String(value))){
                layer.msg('请输入正确数量')
               value='';
            }else {
                value=parseInt(value);
                price=data.unitPirce*value;
            }

           // 得到所在行所有键值
            var field = obj.field; // 得到字段
            // 更新数据中对应的字段
            var update = {};
            update[field] = value;
            update['reconcilePrice'] = price;
            obj.update(update);

        });
        var priceTableIns = priceTb.render({
            elem: '#priceTable'
            , url: "{:url('addPrice')}"
            , method: 'post'
            , toolbar: '#priceToolbarDemo',
            defaultToolbar: []
            , cellMinWidth: 80
            , cols: [[
                {type: 'checkbox', fixed: 'left'},
                {fixed: 'left', field: 'id', title: 'ID', unresize: true, hide: true}
                // ,{field: 'id', width: 80, title: 'ID号', align: 'center'}
                , {field: 'pName', title: '供应商'}
                , {field: 'type',  title: '单据类型',templet:function (d) {
                    if (d.type==1){
                        return'罚款单';
                    }else {
                        return "其他收入单";
                    }
                    }}
                , {field: 'reconcilePrice', title: '对账金额'}
            ]]
            , page: true
        });
        //监听搜索提交
        form.on('submit(priceWebform)', function (data) {
            priceTableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        });
        //表头工具栏事件
        priceTb.on('toolbar(priceTable)', function (obj) {
            var checkStatus = priceTb.checkStatus(obj.config.id);
            console.log(checkStatus)
            switch (obj.event) {
                case 'add':
                    break;
                case 'priceSubt':
                    var data = checkStatus.data;
                    var ids = []
                    if (data.length) {
                        data.forEach(function (value, index) {
                            ids.push(value)
                        })
                        console.log('ids',ids)
                        saveAddMx(ids,2)
                        layer.close(layTip)

                    } else {
                        layer.msg('请选择数据');
                    }

                    break;
                case 'import':

                    break;

            }
            ;
        })

        laydate.render({
            elem:'#reconcileDate',
            format:'yyyy-MM-dd',
            range:"~"
        })
    }
    var is_add=2;
function  saveAddMx(data,type=1) {
let addData=[];
if (data.length){
    for (var i=0;i<data.length;i++){
        let dd1=data[i];
        if (type==1){
            if (dd1.reconcileNum==''){
                layer.msg('数量填写有误');
                return;
            }
            if (Math.abs(dd1.reconcileNum)>Math.abs(dd1.num)){
                layer.msg('数量填写有误');
                return;
            }
            addData.push({sale_hanging_bill_id:dd1.id,
                material_dossier_id:dd1.material_dossier_id,
                punter_id:dd1.punter_id,
                reconcileNum:dd1.reconcileNum,
                reconcilePrice:dd1.reconcilePrice,
                unitPirce:dd1.unitPirce,
                reconcile_type:type
            })
        }else {
            addData.push({punter_ticket_id:dd1.id,
                punter_id:dd1.purveyor_id,
                reconcilePrice:dd1.reconcilePrice,reconcile_type:type
            })
        }

    }

    if (addData.length && is_add==2){

        $.ajax({
            url:"{:url('add')}",
            type:'post',
            dataType:'json',
            data:{add:1,data:addData},
            success:function (res) {
                is_add=1;
                layer.msg(res.msg);
                if (res.code==0){
                    setTimeout(function () {
                        location.reload()
                    },1000)

                }
            },
            error(e){
                is_add=1;
                layer.msg('网络错误,请稍后再试')
            }
        })
    }
}
}
    let is_sure=2;
    function onSure(ids) {
        let id=ids;
        if (!id.length){
            layer.msg('操作有误');
            return;
        }
        if (is_sure==1){
            return;
        }
        is_sure=1;
        $.ajax({
            url:"{:url('onSure')}",
            type:'post',
            dataType:'json',
            data:{id:id.join(',')},
            success:function (res) {
                is_sure=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_sure=2
            }
        })
    }
    let is_cancel=2;
    function onCancel(ids) {
        let id=ids;
        if (!id.length){
            layer.msg('操作有误');
            return;
        }
        if (is_cancel==1){
            return;
        }
        is_cancel=1;
        $.ajax({
            url:"{:url('onCancel')}",
            type:'post',
            dataType:'json',
            data:{id:id.join(',')},
            success:function (res) {
                is_cancel=2;
                layer.msg(res.msg)
                if (res.code == 0) {
                    setTimeout(function () {
                        parent.parent.location.reload();
                    }, 1000);
                }
            },
            error(e){
                layer.msg('网络错误，请稍后重试')
                is_cancel=2
            }
        })
    }

</script>
{/block}
<!-- /脚本 -->